<?php
	include_once "DBProperties.php";
	
function LogPoint( $latitude, $longitude, $speed, $bearing )
	{
		global $databaseName, $connection, $point;
		$thresholdCoords = 0.0001;
		$thresholdBearing = 90;
		
		mysql_select_db($databaseName, $connection);
		
		$thresholdUpperLat = $latitude + $thresholdCoords;
		if ( $thresholdUpperLat > 360 )
		{
			$thresholdUpperLat = $thresholdUpperLat - 360;
		}
		
		$thresholdLowerLat = $latitude - $thresholdCoords;
		if ( $thresholdUpperLat < 0 )
		{
			$thresholdLowerLat = $thresholdLowerLat + 360;
		}
		
		$thresholdUpperLong = $longitude + $thresholdCoords;
		if ( $thresholdUpperLat > 360 )
		{
			$thresholdUpperLong = $thresholdUpperLong - 360;
		}
		
		$thresholdLowerLong = $longitude - $thresholdCoords;
		if ( $thresholdUpperLat < 0 )
		{
			$thresholdLowerLong = $thresholdLowerLong + 360;
		}
		
		$thresholdUpperBear = $bearing + $thresholdBearing;
		if ( $thresholdUpperLat > 360 )
		{
			$thresholdUpperBear = $thresholdUpperBear - 360;
		}
		
		$thresholdLowerBear = $bearing - $thresholdBearing;
		if ( $thresholdUpperLat < 0 )
		{
			$thresholdLowerBear = $thresholdLowerBear + 360;
		}
		
		$sqlStringSelectPoint = "SELECT * FROM ".$point." WHERE Latitude BETWEEN ".$thresholdLowerLat." AND ".$thresholdUpperLat." AND Longitude BETWEEN ".$thresholdLowerLong." AND ".$thresholdUpperLong." AND Bearing BETWEEN ".$thresholdLowerBear." AND ".$thresholdUpperBear."";
		$results = mysql_query($sqlStringSelectPoint);	
		
		$averageSpeed = $speed;
		$averageBearing = $bearing;
		$rowNum = 1;
		
		if ($results != null)
		{
			while ($row = mysql_fetch_array($results))
			{
				$rowNum++;
				$averageSpeed = $averageSpeed + $row['Speed'];
				$averageBearing = $averageBearing + $row['Bearing'];
			}
			
			$sqlStringDeletePoint = "DELETE FROM ".$point." WHERE Latitude BETWEEN ".$thresholdLowerLat." AND ".$thresholdUpperLat." AND Longitude BETWEEN ".$thresholdLowerLong." AND ".$thresholdUpperLong." AND Bearing BETWEEN ".$thresholdLowerBear." AND ".$thresholdUpperBear."";	
			mysql_query($sqlStringDeletePoint);
		}
		
		$averageSpeed = $averageSpeed/$rowNum;
		$averageBearing = $averageBearing/$rowNum;
		
		$sqlStringInsertPoint = "INSERT INTO points (Latitude,Longitude,Speed,Bearing) VALUES (".$latitude.",".$longitude.",".$averageSpeed.", ".$averageBearing.")";		
		mysql_query($sqlStringInsertPoint);
	}
?>